/*
 DLRecyclingDepotLocatorViewController.m
 Date Created: February 23, 2010
 
 Author: Karol Krizka <kkrizka@gmail.com>
 
 Copyright (C) 2010 Green-Power
 
 URL: http://code.google.com/p/green-power
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) a  ny later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 $Id$
 */

#import "DLRecyclingDepotLocatorViewController.h"
#import "DLRecyclingDepot.h"

@implementation DLRecyclingDepotLocatorViewController

@synthesize mapView;

- (void)viewDidLoad {
  [super viewDidLoad];
 
  initialized = NO;
  // Prepare queries
  returnItQuery=[[DLGoogleLocalQuery alloc] initWithQuery:@"return+it"];
  returnItQuery.delegate=self;
  changesQuery=[[DLGoogleLocalQuery alloc] initWithQuery:@"changes"];
  changesQuery.delegate=self;
  bottleDepotQuery=[[DLGoogleLocalQuery alloc] initWithQuery:@"bottle+depot"];
  bottleDepotQuery.delegate=self;
  
  // Start up location manager
  locationManager = [[CLLocationManager alloc] init];
  if(!locationManager.locationServicesEnabled) {
    [self alertManualLocation];
    return;
  }
  locationManager.delegate=self;
  [locationManager startUpdatingLocation];

}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
	
  // TODO Erase previous markers
}

- (void)viewDidUnload {
}

- (void)giveUserControl {
  mapView.zoomEnabled=YES;
  mapView.scrollEnabled=YES;
  mapView.showsUserLocation=YES;
  
  UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"WARNING!"
                                                    message:@"The located depots are not guaranteed to be actual depots. User discretion advised."
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
  [alertView show];
  [alertView release];
  
  initialized=YES;
}

- (void)alertManualLocation {
  NSLog(@"initialized");
  if(initialized) return;
    NSLog(@"not initialized");
  UIAlertView *errorView=[[UIAlertView alloc] initWithTitle:@"No Location"
                                                    message:@"Please locate yourself on the map"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
  [errorView show];
  [errorView release];
  [self giveUserControl];
}
- (void)handleNewLocation:(CLLocationCoordinate2D)location {
  [returnItQuery lookUpAtLocation:location];
  [changesQuery lookUpAtLocation:location];
  [bottleDepotQuery lookUpAtLocation:location];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
  if(error.code==kCLErrorDenied || // Denied by user, so request manual location
     error.code==kCLErrorNetwork) // Network error, that is pretty bad too
    [self alertManualLocation];
  
  [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSLog(@"did update");
  if(!initialized) {
#if TARGET_IPHONE_SIMULATOR
    // On iPhone Simulator, the default location is the Apple HQ in California
    // But our app is designed for BC, so zoom in there instead
    // KK's House
   // newLocation=[[[CLLocation alloc] initWithLatitude:49.28 longitude:-122.98] autorelease];
#endif // TARGET_IPHONE_SIMULATOR
 
 MKCoordinateRegion region;
    region.center=[newLocation coordinate];
    region.span.latitudeDelta=0.05;
    region.span.longitudeDelta=0.05;
    [mapView setRegion:region animated:NO];
    
    [self giveUserControl];
    
 
    }

  [self handleNewLocation:newLocation.coordinate];
}

- (void)googleLocalQuery:(DLGoogleLocalQuery *)query finishedWithParseError:(NSError *) error {
  NSLog(@"Eror parsing Google Local Search response. %@",error);
}

- (void)googleLocalQuery:(DLGoogleLocalQuery *)query finishedWithStatus:(NSUInteger)status results:(NSArray *)depots {
  for(DLRecyclingDepot *depot in depots) {
    BOOL found=NO;
    for(DLRecyclingDepot *existingDepot in mapView.annotations) {
      if([existingDepot isKindOfClass:[DLRecyclingDepot class]] && // Make sure not to check with a non-depot. annotations also contains user location
         [existingDepot.name isEqualToString:depot.name] &&
         [existingDepot.address isEqualToString:depot.address]) {
        found=YES;
        break;
      }
    }
    if(found) continue;
    // Haven't returned, so this depot is new
    [mapView addAnnotation:depot];
    NSLog(@"Added %@ from query %@",depot.name,query.queryName);
  }
}

- (void)mapView:(MKMapView *)localMapView regionDidChangeAnimated:(BOOL)animated {
  if(initialized) {
//    NSLog(@"MOVED! %f %f",localMapView.region.span.latitudeDelta,localMapView.region.span.longitudeDelta);
    if(localMapView.region.span.latitudeDelta>0.2) return;
    if(localMapView.region.span.longitudeDelta>0.2) return;
    
    [self handleNewLocation:localMapView.region.center];  
  }
}

- (void)mapViewDidFailLoadingMap:(MKMapView *)localMapView withError:(NSError*)error {
  // TODO Better network detection than this..
  UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"No Network"
                                                    message:@"You require a network connection to use the map functionality"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
  [alertView show];
  [alertView release];
  [locationManager stopUpdatingLocation];
}

- (void)mapViewDidFinishLoadingMap:(MKMapView *)localMapView {
  if(!initialized)
    [locationManager startUpdatingLocation];
}

- (void)dealloc {
  [super dealloc];
  
  [mapView release];  
  [locationManager release];
  
  [changesQuery release];
  [returnItQuery release];
  [bottleDepotQuery release];
}


@end
